<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="3" :xs="24">
        <el-input
          v-model="taskName"
          placeholder="请输入任务名称或编号"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 15px"
        />
        <el-tree ref="tree" node-key="id" highlight-current  :data="filteredTasks"
                 :default-checked-keys="checkDefault1"
                 :props="defaultProps" @node-click="productSearchClick">
        <template v-slot="{node}">
          <span :title="node.label" class="node-label">{{node.label}}</span>
        </template>
        </el-tree>
      </el-col>
      <!--用户数据-->
      <el-col :span="21" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="工单名称" prop="workOrderName">
            <el-input
              v-model="queryParams.workOrderName"
              placeholder="请输入工单名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="工单状态" prop="workOrderStauts">
            <el-select v-model="queryParams.workOrderStauts" placeholder="请选择工单状态">
              <el-option
                v-for="dict in workOrderStautsS"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="wordOrderList" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" />
          <el-table-column label="mes批次号" align="center" prop="mesNo" width="150"/>
          <el-table-column label="工单名称" align="center" prop="workOrderName" show-overflow-tooltip width="300" />
          <el-table-column label="工单编号" align="center" prop="workOrderNo" show-overflow-tooltip width="260" />
          <el-table-column label="工序编号" align="center" prop="processNo" width="180" />
          <el-table-column label="工序名称" align="center" prop="processName" width="180"/>
          <el-table-column label="生产总车序" align="center" prop="ji" width="130" />
          <el-table-column label="任务车序" align="center" prop="taskJi" width="130" />
          <el-table-column label="第几道工序" align="center" prop="productionLineSequence" width="130" />
          <el-table-column label="添加的人数" align="center" prop="extraPer" width="130" />
          <el-table-column label="工单状态" align="center" prop="workOrderStauts" :formatter="workStautsFomatter" width="130"/>
          <el-table-column label="预计开始时间" align="center"  prop="exStartTime" width="180"/>
          <el-table-column label="预计完成时间" align="center"  prop="exEndTime" width="180" />
          <el-table-column label="实际开始时间" align="center"  prop="acStartTime" width="180" />
          <el-table-column label="实际完成时间" align="center"  prop="acEndTime" width="180" />
          <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['zndd:solutionset:edit']"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 修改报工信息状态框 -->
      <el-dialog :title="title" :visible.sync="open" width="380px" append-to-body>
        <el-form ref="form" align="center" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="工单状态" prop="workOrderStauts">
            <el-select v-model="form.workOrderStauts" placeholder="请选择工单状态">
              <el-option
                v-for="dict in workOrderStautsS"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
                :disabled="dict.disabled"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog style="align-content: center;" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的工单信息
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listInfo ,tasklist,workOderlist,updateWorkOderInfo,exportData} from "@/api/zndd/intelligence/reportingProcess";
import { listWorkorder, getWorkorder, delWorkorder, addWorkorder, updateWorkorder } from "@/api/zndd/work/workorder";

export default {
  name: "reportingProcess",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //工单状态数据
      workOrderStautsS: [],
      // 总条数
      total: 0,
      // 用户表格数据
      wordOrderList: [],
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 任务名称
      taskName: undefined,
      filteredTasks: [],
      tasks: [],
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 树配置
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checkDefault1: [],//存放默认选中节点的id
      currentWTaskId: undefined,
      originalWorkOrderStauts: undefined, // 用于存储原始状态
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/zndd/reporting/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        workOrderName: undefined,
        workOrderStauts: undefined,
        taskId: undefined,
      },
      // 表单校验
      rules: {
        // userName: [
        //   { required: true, message: "用户名称不能为空", trigger: "blur" },
        //   { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        // ],
      }
    };
  },
  created() {
    // 获取报工信息
    this.getList();
    //获取任务列表信息
    this.getListInfo();
    // 获取字典表中产线类型
    this.getDicts("zndd_worker_order_status").then(response => {
      this.workOrderStautsS = response.data;
    });
  },
  // 查询任务名称
  watch: {
    taskName(newVal) {
      this.queryParams.name = newVal;
      console.log(this.queryParams.name); // 添加日志输出，确保监听器生效
      this.getListInfo();
    }
  },
  methods: {
    //格式化问题类型
    workStautsFomatter(row, column){
      var ws = null;
      console.log(this.workStauts)
      this.workOrderStautsS.forEach(workStauts => {
        if (workStauts.dictValue == row.workOrderStauts) {
          ws = workStauts;
        }
      });
      if(ws == null){
        return "";
      }else{
        if(ws.dictValue==1){
          return <el-tag  type="danger">未就绪</el-tag>;
        }else if(ws.dictValue==2){
          return <el-tag>就绪</el-tag>;
        }else if(ws.dictValue==3){
          return <el-tag type="success">进行中</el-tag>;
        }else if(ws.dictValue==4){
          return <el-tag type="info">已完成</el-tag>;
        }else if(ws.dictValue==5){
          return <el-tag type="warning">异常</el-tag>;
        }
        return ws.dictLabel;
      }
    },
/*     filterTasks(query) {
      console.log('filterTasks called with query:', query); // 添加日志输出，确保方法被调用
      if (!query) {
        this.filteredTasks = this.tasks;
      } else {
        console.log(this.filteredTasks)
        console.log(this.tasks)
        const filterTree = (nodes) => {
          return nodes.filter(node => {
            // 如果节点本身匹配，则直接包含
            if (node.label.includes(query)) {
              return true;
            }
            // 否则检查子节点是否匹配
            if (node.children && node.children.length > 0) {
              node.children = filterTree(node.children);
              return node.children.length > 0;
            }
            return false;
          });
        };
        this.filteredTasks = filterTree(this.tasks);
      }
    }, */
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      tasklist(this.queryParams).then(response => {
          this.wordOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 查询任务信息列表
    getListInfo() {
      listInfo(this.queryParams.name).then(response => {
        var list = [];
        response.forEach(row => {
          list.push({
            label: row.name,
            value: row.id,
            id: row.id,
            // children:row.id,
          })
        });
        console.log(list)
        this.tasks = list;
        this.filteredTasks=list;
        // // 设置默认的产品类型
        if (list.length > 0) {
          this.queryParams.taskId = list[0].id;
          this.currentWTaskId = list[0].id;
        }
        this.checkDefault1=[this.currentWTaskId];
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.currentWTaskId);
        })
        console.log( this.checkDefault1)
        this.getList();
      });
    },
    productSearchClick(data){
      this.queryParams.taskId=data.value;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        mesNo: null,
        taskNo: null,
        taskId: null,
        processId: null,
        workOrderName: null,
        workOrderNo: null,
        workOrderStauts: null,
        exStartTime: null,
        exEndTime: null,
        sexStartTime: null,
        sexEndTime: null,
        acStartTime: null,
        acEndTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    taskClick(taskId){
      this.queryParams.taskId = taskId;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.taskId = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    // /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   getUser().then(response => {
    //     this.postOptions = response.posts;
    //     this.roleOptions = response.roles;
    //     this.open = true;
    //     this.title = "添加用户";
    //     this.form.password = this.initPassword;
    //   });
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWorkorder(id).then(response => {
        this.form = response.data;
        this.originalWorkOrderStauts = this.form.workOrderStauts; // 保存原始状态        // 根据当前工单的状态值来决定是否禁用状态1和状态2
        if (this.form.workOrderStauts === '1') {
          this.workOrderStautsS.forEach(dict => {
            dict.disabled = true;
          });
        }else if (this.form.workOrderStauts === '2'){
          this.workOrderStautsS.forEach(dict => {
            if (dict.dictValue === '3'){
              dict.disabled = false;
            }else {
              dict.disabled = true;
            }
          });
        } else if(this.form.workOrderStauts === '4'){
          this.workOrderStautsS.forEach(dict => {
              dict.disabled = true;
          });
        }else if(this.form.workOrderStauts === '3'){
          this.workOrderStautsS.forEach(dict => {
            if (dict.dictValue > '3') {
              dict.disabled = false;
            }else {
              dict.disabled = true;
            }
          });
        }else if(this.form.workOrderStauts === '5'){
          this.workOrderStautsS.forEach(dict => {
            if (dict.dictValue === '3' || dict.dictValue === '4') {
              dict.disabled = false;
            }else {
              dict.disabled = true;
            }
          });
        }
        this.open = true;
        this.title = "修改工单状态";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.workOrderStauts === this.originalWorkOrderStauts) {
        this.$message.warning('状态没有发生变化，无需提交');
        return; // 如果状态没有变化，直接返回，不执行后续操作
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          updateWorkOderInfo(this.form).then(response => {
            console.log(response)
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zndd/reporting/export', {
        ...this.queryParams
      }, `workOrder_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "工单信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('zndd/reporting/importTemplate', {
      }, `workOrderStatus_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="css" scoped>

::v-deep .el-tree-node__content:hover{
background-color: #409EFF;
color: #ffffff;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
  background-color: #409EFF;
  color: #ffffff;
}
/* 自定义滚动条样式 */
::v-deep ::-webkit-scrollbar {
  width: 12px; /* 水平滚动条的宽度 */
  height: 12px; /* 垂直滚动条的高度 */
  cursor: pointer; /* 鼠标靠近滚动条时变为小手样式 */
}

::v-deep ::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道的颜色 */
  cursor: pointer; /* 鼠标靠近滚动条轨道时变为小手样式 */
}

::v-deep ::-webkit-scrollbar-thumb {
  background: #888; /* 滚动条滑块的颜色 */
  border-radius: 6px; /* 滚动条滑块的圆角 */
  cursor: pointer; /* 鼠标靠近滚动条滑块时变为小手样式 */
}

::v-deep ::-webkit-scrollbar-thumb:hover {
  background: #555; /* 滚动条滑块悬停时的颜色 */
  cursor: pointer; /* 鼠标悬停在滚动条滑块上时仍保持小手样式 */
}
.node-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
